package com.zny.sescore.controller;

import com.zny.sescore.model.ApiResult;
import com.zny.sescore.model.CodeName;
import com.zny.sescore.rule.constant.IRuleConstant;
import com.zny.sescore.rule.constant.RuleConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @version: V1.0
 * @author: zhangnayi
 * @className: RuleController
 * @packageName: com.palmdoctor.mb.base.rule
 * @description:
 * @data: 2021-08-09 14:03
 **/
@Slf4j
@Api(tags = "规则引擎接口")
@RestController
@RequestMapping("/rule")
public class ConstantController extends BaseController {

    private static BlockingQueue<RuleConstantUnit> CONSTANTS = new LinkedBlockingQueue<>();

    @Data
    public static class RuleConstantUnit {

        private String code;

        private String name;

        private List<CodeName> valueList;
    }


    @GetMapping("/constant_list")
    @ApiOperation("查询系统枚举列表")
    public ApiResult<Collection<RuleConstantUnit>> findConstantist() {
        return ApiResult.success(CONSTANTS);
    }

    static {
        Package pkg = IRuleConstant.class.getPackage();
        Reflections reflections = new Reflections(pkg.getName());
        reflections.getTypesAnnotatedWith(RuleConstant.class)
                .forEach(clz -> {
                    try {
                        if (clz.isEnum()) {
                            RuleConstant annotation = clz.getAnnotation(RuleConstant.class);
                            RuleConstantUnit constantUnit = new RuleConstantUnit();
                            constantUnit.setCode(annotation.value());
                            constantUnit.setName(annotation.name());
                            Object[] objects = clz.getEnumConstants();
                            IRuleConstant constant = ((IRuleConstant) objects[0]);
                            constantUnit.setValueList(constant.codeNames());
                            CONSTANTS.add(constantUnit);
                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }
                });
    }

}